package com.example.food_contract_system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.food_contract_system.domain.Agency;
import com.example.food_contract_system.domain.Boss;
import com.example.food_contract_system.domain.Food;
import com.example.food_contract_system.domain.SysRegion;
import com.example.food_contract_system.mapper.AgencyMapper;
import com.example.food_contract_system.mapper.FoodMapper;
import com.example.food_contract_system.mapper.SysRegionMapper;
import com.example.food_contract_system.service.BossService;
import com.example.food_contract_system.mapper.BossMapper;
import com.example.food_contract_system.util.R;
import com.example.food_contract_system.vo.AddFoodVo;
import com.example.food_contract_system.vo.BossUpdateVo;
import com.example.food_contract_system.vo.FoodByImgListVo;
import com.example.food_contract_system.vo.ManagerAgencyListVo;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author Lhy
* @description 针对表【boss】的数据库操作Service实现
* @createDate 2023-07-06 09:22:01
*/
@Service
public class BossServiceImpl extends ServiceImpl<BossMapper, Boss> implements BossService{

    @Autowired
    private AgencyMapper agencyMapper;
    @Autowired
    private BossMapper bossMapper;
    @Autowired
    private SysRegionMapper sysRegionMapper;
    @Autowired
    private FoodMapper foodMapper;

    /**
     * 将经销商的信息组装成树形结构
     * @return
     */
    @Override
    public R getManagerAgencyList() {
        // 1. 首先可以获取到总经销商的分布
        //1.1 获取到总经销商的所在地区id
        List<Agency> agenciesBoss = agencyMapper.selectList(null);
        List<ManagerAgencyListVo> managerAgencyListVos = agenciesBoss.stream().filter(agency -> {
            return agency.getAQx() == 0;
        }).map(agency -> {
            ManagerAgencyListVo managerAgencyListVo = new ManagerAgencyListVo();
            // 1.2 根据获取到的地区id来获取地区的名称
            SysRegion sysRegion = sysRegionMapper.selectOne(new QueryWrapper<SysRegion>()
                    .eq("region_id", agency.getARNumber()));
            if (sysRegion != null) {
                managerAgencyListVo.setRegion(sysRegion.getRegionName());
            }
            managerAgencyListVo.setName(agency.getAName());
            managerAgencyListVo.setPhone(agency.getAAccount());
            managerAgencyListVo.setStatus(
                    agency.getAStatus().equals("0") ? "待审核" : (agency.getAStatus().equals("1") ? "通过" : "驳回")
            );
            managerAgencyListVo.setImg(agency.getAPicture());
            managerAgencyListVo.setId(agency.getAId());

            managerAgencyListVo.setChildren(
                    getChildren(agency, agenciesBoss).size() > 0 ? getChildren(agency, agenciesBoss) : null
            );

            return managerAgencyListVo;
        }).collect(Collectors.toList());

        if (managerAgencyListVos.size()>0){
            return R.ok().put("data",managerAgencyListVos);
        }
        return R.error(500,"数据错误");
    }

    @Override
    public R updateStatus(String opt, String id) {
        agencyMapper.updateStatus(opt,id);
        return R.ok();
    }

    @Override
    public R deleteAgency(String password, String id, String bid) {
        // 判断二级密码是否正确
        Boss boss = bossMapper.selectOne(new QueryWrapper<Boss>()
                .eq("b_id", bid));
        if (boss!= null){
            if (boss.getBPasswordTwo().equals(password)){
                //密码通过
                // 根据id获取该经销商的信息
                Agency agency = agencyMapper.selectOne(new QueryWrapper<Agency>()
                        .eq("a_id", id));
                // 判断是不是总经销商
                if (!agency.getAParentId().equals("-1")){
                    // 不是，则是经销商，可以进行删除
                    int i = agencyMapper.deleteByIdByMyself(id);
                    if (i > 0){
                        return R.ok().put("msg","删除成功!");
                    }
                    return R.error(500,"删除失败！");
                }else{
                    Agency aParentId = agencyMapper.selectOne(new QueryWrapper<Agency>()
                            .eq("a_parent_id", id));
                    if (aParentId == null){
                        int i = agencyMapper.deleteByIdByMyself(id);
                        if (i > 0){
                            return R.ok().put("msg","删除成功!");
                        }
                        return R.error(500,"删除失败！");
                    }
                    return R.error(500,"总经销商无法删除!");
                }
            }else{
                return R.error(500,"密码错误!");
            }
        }else {
            return R.error(500,"数据错误!");
        }
    }

    @Override
    public R getStatusList(String status) {
        if (StrUtil.isNotBlank(status)){
            List<Agency> agencies = agencyMapper.selectList(new QueryWrapper<Agency>()
                    .eq("a_status", status));
            if (agencies.size() > 0){
                List<ManagerAgencyListVo> managerAgencyListVos = agencies.stream().map(agency -> {
                    ManagerAgencyListVo managerAgencyListVo = new ManagerAgencyListVo();
                    managerAgencyListVo.setId(agency.getAId());
                    managerAgencyListVo.setName(agency.getAName());
                    managerAgencyListVo.setPhone(agency.getAAccount());
                    managerAgencyListVo.setImg(agency.getAPicture());
                    managerAgencyListVo.setStatus(
                            status.equals("0") ? "待审核" : (status.equals("1") ? "通过" : "驳回")
                    );

                    SysRegion sysRegion = sysRegionMapper.selectOne(new QueryWrapper<SysRegion>()
                            .eq("region_id", agency.getARNumber()));

                    if (sysRegion != null) {
                        managerAgencyListVo.setRegion(sysRegion.getRegionName());
                    }

                    return managerAgencyListVo;
                }).collect(Collectors.toList());

                if (managerAgencyListVos.size() > 0){
                    return R.ok().put("data",managerAgencyListVos);
                }
                return R.error();
            }
        }
        return R.error();
    }

    @Override
    public R batchApproval(String list, String opt) {
        List<ManagerAgencyListVo> managerAgencyListVos = new ArrayList<>();
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(list);
            JsonNode regionNode = jsonNode.get("list");

            if (regionNode.isArray()) {
                Iterator<JsonNode> elements = regionNode.elements();
                while (elements.hasNext()){
                    JsonNode next = elements.next();
                    ManagerAgencyListVo managerAgencyListVo = new ManagerAgencyListVo();

                    managerAgencyListVo.setName(next.get("name").asText());
                    managerAgencyListVo.setRegion(next.get("region").asText());
                    managerAgencyListVo.setId(next.get("id").asText());
                    managerAgencyListVo.setStatus(opt);

                    managerAgencyListVos.add(managerAgencyListVo);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (managerAgencyListVos.size() > 0){
            for (ManagerAgencyListVo managerAgencyListVo : managerAgencyListVos) {
                agencyMapper.updateStatus(opt,managerAgencyListVo.getId());
            }
            return R.ok().put("msg","批量完成!");
        }
        return R.error();
    }

    @Override
    public R addFood(AddFoodVo addFoodVo) {
        if (addFoodVo != null){
            Food food = new Food();

            food.setFId(0);
            food.setFName(addFoodVo.getName());
            food.setFNum(addFoodVo.getNum());
            food.setFType(addFoodVo.getType());
            food.setFPrice(addFoodVo.getPrice());
            food.setFDesc(addFoodVo.getDesc());
            food.setFNumber(addFoodVo.getFdate());

            // 创建SimpleDateFormat对象，指定日期格式
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            // 格式化日期
            String formattedDate = sdf.format(addFoodVo.getDate());

            food.setFDate(formattedDate);

            List<String> uploadList = addFoodVo.getUploadList();
            StringJoiner sj = new StringJoiner(",");
            for (String item : uploadList) {
                sj.add("http://localhost:8081/index/"+item);
            }

            food.setFImg(sj.toString());

            int insert = foodMapper.insert(food);
            if (insert > 0){
                return R.ok().put("msg","创建成功!");
            }
        }
        return R.error();
    }

    @Transactional
    @Override
    public R updateFoodMsg(FoodByImgListVo foodByImgListVo) {
        Food food = new Food();

        food.setFId(foodByImgListVo.getFId());
        food.setFImg(foodByImgListVo.getFImg().stream().map(String::valueOf).collect(Collectors.joining(",")));

        // 创建SimpleDateFormat对象，指定日期格式
        SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");

        try {
            Date date = inputFormat.parse(foodByImgListVo.getFDate());
            // 格式化日期
            String formattedDate = outputFormat.format(date);

            food.setFDate(formattedDate);

        } catch (Exception e) {
            e.printStackTrace();
        }

        food.setFDesc(foodByImgListVo.getFDesc());
        food.setFName(foodByImgListVo.getFName());
        food.setFType(foodByImgListVo.getFType());
        food.setFPrice(Double.parseDouble(foodByImgListVo.getFPrice()));
        food.setFNum(foodByImgListVo.getFNum());

        int i = foodMapper.updateByIdMyself(food);
        if (i != 0){
            return R.ok().put("msg","更新成功!");
        }
        return R.error();
    }

    @Override
    public R getOrderAgencyList() {
        // 1. 首先可以获取到总经销商的分布
        //1.1 获取到总经销商的所在地区id
        List<Agency> agenciesBoss = agencyMapper.selectListMyself("1");
        List<ManagerAgencyListVo> managerAgencyListVos = agenciesBoss.stream().filter(agency -> {
            return agency.getAQx() == 0;
        }).map(agency -> {
            ManagerAgencyListVo managerAgencyListVo = new ManagerAgencyListVo();
            // 1.2 根据获取到的地区id来获取地区的名称
            SysRegion sysRegion = sysRegionMapper.selectOne(new QueryWrapper<SysRegion>()
                    .eq("region_id", agency.getARNumber()));
            if (sysRegion != null) {
                managerAgencyListVo.setRegion(sysRegion.getRegionName());
            }
            managerAgencyListVo.setName(agency.getAName());
            managerAgencyListVo.setPhone(agency.getAAccount());
            managerAgencyListVo.setStatus(
                    agency.getAAccountStatus().equals("0") ? "正常" : "异常"
            );
            managerAgencyListVo.setImg(agency.getAPicture());
            managerAgencyListVo.setId(agency.getAId());

            managerAgencyListVo.setChildren(
                    getChildrenByOrder(agency, agenciesBoss).size() > 0 ? getChildrenByOrder(agency, agenciesBoss) : null
            );

            return managerAgencyListVo;
        }).collect(Collectors.toList());

        if (managerAgencyListVos.size()>0){
            return R.ok().put("data",managerAgencyListVos);
        }
        return R.error(500,"数据错误");
    }

    @Override
    public R getBoss(String bId) {
        Boss boss = bossMapper.selectOne(new QueryWrapper<Boss>()
                .eq("b_id", bId));
        if (boss != null){
            return R.ok().put("data",boss);
        }
        return R.error();
    }

    @Override
    public R updatePwd(BossUpdateVo bossUpdateVo, String bid) {
        Boss boss = bossMapper.selectOne(new QueryWrapper<Boss>()
                .eq("b_id", bid));
        if (boss != null){
            if (!bossUpdateVo.getKey().equals(boss.getBPassword())){
                return R.error(500,"您的密码不正确!");
            }else{
                bossMapper.updateMyself(bid,bossUpdateVo.getValue());
                return R.ok().put("msg","修改成功");
            }
        }
        return R.error();
    }

    @Override
    public R updatePwd2(BossUpdateVo bossUpdateVo, String bid) {
        Boss boss = bossMapper.selectOne(new QueryWrapper<Boss>()
                .eq("b_id", bid));
        if (boss != null){
            if (!bossUpdateVo.getKey().equals(boss.getBPassword())){
                return R.error(500,"您的密码不正确!");
            }else{
                bossMapper.updateMyself2(bid,bossUpdateVo.getValue());
                return R.ok().put("msg","修改成功");
            }
        }
        return R.error();
    }


    private List<ManagerAgencyListVo> getChildren(Agency agency, List<Agency> agenciesBoss) {
        List<SysRegion> sysRegions = getChildrenRegion(agency);

        List<ManagerAgencyListVo> managerAgencyListVos = new ArrayList<>();
        for (Agency boss : agenciesBoss) {
            if (boss.getAQx() != 0){
                ManagerAgencyListVo managerAgencyListVo = new ManagerAgencyListVo();
                for (SysRegion sysRegion : sysRegions) {
                    if (sysRegion.getRegionId().equals(boss.getARNumber())) {
                        managerAgencyListVo.setStatus(
                                boss.getAStatus().equals("0") ? "待审核" : (boss.getAStatus().equals("1") ? "通过" : "驳回")
                        );
                        managerAgencyListVo.setName(boss.getAName());
                        managerAgencyListVo.setPhone(boss.getAAccount());
                        managerAgencyListVo.setRegion(sysRegion.getRegionName());
                        managerAgencyListVo.setImg(boss.getAPicture());
                        managerAgencyListVo.setId(boss.getAId());
                    }
                }
                if (managerAgencyListVo.getRegion() != null){
                    managerAgencyListVos.add(managerAgencyListVo);
                }
            }
        }
        return managerAgencyListVos;
    }

    private List<ManagerAgencyListVo> getChildrenByOrder(Agency agency, List<Agency> agenciesBoss) {
        List<SysRegion> sysRegions = getChildrenRegion(agency);

        List<ManagerAgencyListVo> managerAgencyListVos = new ArrayList<>();
        for (Agency boss : agenciesBoss) {
            if (boss.getAQx() != 0){
                ManagerAgencyListVo managerAgencyListVo = new ManagerAgencyListVo();
                for (SysRegion sysRegion : sysRegions) {
                    if (sysRegion.getRegionId().equals(boss.getARNumber())) {
                        managerAgencyListVo.setStatus(
                                boss.getAAccountStatus().equals("0") ? "正常" : "异常"
                        );
                        managerAgencyListVo.setName(boss.getAName());
                        managerAgencyListVo.setPhone(boss.getAAccount());
                        managerAgencyListVo.setRegion(sysRegion.getRegionName());
                        managerAgencyListVo.setImg(boss.getAPicture());
                        managerAgencyListVo.setId(boss.getAId());
                    }
                }
                if (managerAgencyListVo.getRegion() != null){
                    managerAgencyListVos.add(managerAgencyListVo);
                }
            }
        }
        return managerAgencyListVos;
    }

    private List<SysRegion> getChildrenRegion(Agency agency) {
        List<SysRegion> result = new ArrayList<>();

        List<SysRegion> sysRegions = sysRegionMapper.selectList(new QueryWrapper<SysRegion>()
                .eq("region_parent_id", agency.getARNumber()));

        for (SysRegion sysRegion : sysRegions) {
            result.add(sysRegion);
            List<SysRegion> regions = sysRegionMapper.selectList(new QueryWrapper<SysRegion>()
                    .eq("region_parent_id", sysRegion.getRegionId()));
            if (regions.size() > 0){
                for (SysRegion region : regions) {
                    result.add(region);
                }
            }
        }
        return result;
    }
}
